package com.hsy.directseeding.main.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPPicassoUtil;
import com.hsy.directseeding.R;
import com.hsy.directseeding.common.CommonBaseFragment;
import com.hsy.directseeding.common.Consts;
import com.hsy.directseeding.main.MainListGson;
import com.hsy.directseeding.main.player.PlayerVideoActivity;
import com.hsy.directseeding.utils.CommonUtils;
import com.hsy.directseeding.utils.HttpUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/9.
 */
public class DirectSeedingListFragment extends CommonBaseFragment {
    public DirectSeedingListFragment() {
    }

    @SuppressLint("ValidFragment")
    public DirectSeedingListFragment(String catId) {
        this.catId = catId;
    }

    private String catId = "";

    private final static int SEEDING_TIME = 100;
    protected GridView uavGrid;
    private List<MainListGson.Goods> listData = new ArrayList<>();
    private LayoutInflater inflater;
    private AdapterGrid adapterGrid;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (handler.hasMessages(SEEDING_TIME)) {
                handler.removeMessages(SEEDING_TIME);
                DPLogUtil.d("onReceive handler");
            }
        }
    };
    private DPHttpUtil.HttpCallback callBack = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            if (handler.hasMessages(SEEDING_TIME)) {
                handler.removeMessages(SEEDING_TIME);
            }
            MainListGson.Result result = DPGsonUtil.fromJson(response, MainListGson.Result.class);
            listData = result.getGoods();
            adapterGrid = new AdapterGrid();
            uavGrid.setAdapter(adapterGrid);
            CommonUtils.hideProgressDialog();
            handler.sendEmptyMessageDelayed(SEEDING_TIME, 5 * 1000);
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            if (handler.hasMessages(SEEDING_TIME)) {
                handler.removeMessages(SEEDING_TIME);
            }
            CommonUtils.hideProgressDialog();
            handler.sendEmptyMessageDelayed(SEEDING_TIME, 5 * 1000);
        }
    };

    @Override
    public void onStop() {
        super.onStop();
        if (handler.hasMessages(SEEDING_TIME)) {
            handler.removeMessages(SEEDING_TIME);
            DPLogUtil.d("onStop handler");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getAttchedActivity().unregisterReceiver(receiver);
        if (handler.hasMessages(SEEDING_TIME)) {
            handler.removeMessages(SEEDING_TIME);
            DPLogUtil.d("onDestroy handler");
        }
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (SEEDING_TIME == msg.what) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("token", CommonUtils.getToken(getAttchedActivity()));
                map.put("cat_id", catId);
                HttpUtil.httpPostWithParams(getAttchedActivity(), 0, Consts.Apis.POST_MAIN_LIST, map, callBack);

            }
        }
    };

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_uav;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        inflater = LayoutInflater.from(getAttchedActivity());
        uavGrid = (GridView) view.findViewById(R.id.uav_grid);
        uavGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (listData.get(position).getLive_status().equals("1")) {
                    if (listData.get(position).getQiniu_live() != null) {
                        Intent intent = new Intent(getAttchedActivity(), PlayerVideoActivity.class);
                        intent.putExtra("videoUrl", listData.get(position).getQiniu_live().getHttp());
                        intent.putExtra("videoName", listData.get(position).getName());
                        startActivity(intent);
                    } else {
                        showToast("暂无直播");
                    }
                } else {
                    showToast("暂无直播");
                }


            }
        });
        LinearLayout empty = F(R.id.empty);
        uavGrid.setEmptyView(empty);
        getAttchedActivity().registerReceiver(receiver, new IntentFilter(Consts.Actions.ACTION_AUTH_FAILURE));
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (!isEmpty(catId)) {
                CommonUtils.showProgressDialog(getAttchedActivity());
                Map<String, String> map = new HashMap<String, String>();
                map.put("token", CommonUtils.getToken(getAttchedActivity()));
                map.put("cat_id", catId);
                HttpUtil.httpPostWithParams(getAttchedActivity(), 0, Consts.Apis.POST_MAIN_LIST, map, callBack);
            }

        } else {
            if (handler.hasMessages(SEEDING_TIME)) {
                handler.removeMessages(SEEDING_TIME);
                DPLogUtil.d("isVisibleToUser uav handler");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message msg) {

    }

    private class AdapterGrid extends BaseAdapter {

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int i) {
            return listData.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            view = inflater.inflate(R.layout.item_grid, null);
            ImageView image = (ImageView) view.findViewById(R.id.image);
            ImageView video_player = (ImageView) view.findViewById(R.id.video_player);
            TextView title = (TextView) view.findViewById(R.id.title);
            title.setText(listData.get(position).getName());
            if (listData.get(position).getLive_status().equals("1")) {
                video_player.setVisibility(View.VISIBLE);

                int i = (int) (10000 + Math.random() * 100000);
                //得到long类型当前时间
                long l = System.currentTimeMillis();
//new日期对象
                Date date = new Date(l);
//转换提日期输出格式
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

                DPLogUtil.d("image==" + listData.get(position).getQiniu_snapshot() + "?r=" + dateFormat.format(date) + i);

                DPLogUtil.d("刷新图片");

                DPPicassoUtil.with(getAttchedActivity()).load(listData.get(position).getQiniu_snapshot() + "?r=" + dateFormat.format(date) + i).into(image);

            } else {
                video_player.setVisibility(View.GONE);
                image.setImageResource(R.mipmap.defualt_video_image);
            }

            return view;
        }
    }
}
